﻿/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Меню форума Vingrad.
 *
 * The Initial Developer of the Original Code is
 * Jefim Borissov.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor (s):
 * Daniel Abramov
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */

// Разнообразные мелкие утилиты-функции
var utils = {
  // Ветвь настроек (для getPrefsBranch ())
  _branch : null,

  // Получить ветвь настроек
  getPrefsBranch : function () {
  	if (this._branch != null) {
	  return this._branch;  
	} else {
  	  this._branch = Components.classes["@mozilla.org/preferences-service;1"].
          getService(Components.interfaces.nsIPrefService).
	        getBranch ("vingradmenu.");
	  return this._branch;
	}
  },
  // Получить буфер обмена
  getClipboard : function () {
    return Components.classes["@mozilla.org/widget/clipboardhelper;1"].
	         getService (Components.interfaces.nsIClipboardHelper);
  },
  // Получить сервис промптов и алертов :)
  getPromptService: function () {
    return Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
  },
  // Закодировать URL-строкой выделенный текст и обрезать пробелы
  getSelectionForSearch : function () {
    var q = utils.trim (window.content.getSelection ().toString ());
    return q;
  },
  // Папка расширения
  getExtFolder: function () {
    var file = Components.classes["@mozilla.org/file/directory_service;1"]
           .getService(Components.interfaces.nsIProperties)
           .get("ProfD", Components.interfaces.nsIFile); // профиль
    file.append("extensions");   // extensions sub-directory
    file.append("vingradmenu@jefim.borissov");   // GUID of your extension
    return file;
  },
  // файловый поток для записи
  getFileStream: function () {
    return Components.classes["@mozilla.org/network/file-output-stream;1"]
               .createInstance(Components.interfaces.nsIFileOutputStream);
  },
  // Обрезать пробелы в строке
  trim: function (s) {
	while (s.substring (0,1) == ' ') {
	  s = s.substring (1, s.length);
	}
	while (s.substring (s.length-1, s.length) == ' ') {
	  s = s.substring (0, s.length-1);
	}
	return s;
  },
  // обычный промт со значением по умолчанию
  refiningPrompt: function (title, message, defaultVal) {
    var boxedVal = {value: defaultVal};
    if (this.getPromptService ().prompt (window, title, message, boxedVal, '', {}))
      return boxedVal.value;
    else return null;
  },
  // Yep? Nope?
  yesNoPrompt: function (title, message) {
    var ps = this.getPromptService ();
    return (ps.confirmEx(window, title, message, ps.STD_YES_NO_BUTTONS, '', '', '', '', {}) == 0) ? true : false;
  },
  tryParseTopicId: function () {
    var loc = content.window.location;
    try {
        if (loc.host == "forum.vingrad.ru") {
            if (loc.pathname.indexOf (".html") != -1) { // ЧПУ
                var matches = loc.pathname.match(/.*\/t(opic)?-(\d+)(\/|\.html).*/);
                if (matches != null && matches[2] != null) return matches[2];
            } else if (loc.search.indexOf ("showtopic") != -1) {
                var matches = loc.search.match(/.*(\?|\&)showtopic=(\d*)(\&)?.*/);
                if (matches != null && matches[2] != null) return matches[2];
            } else if (loc.search.indexOf ("act=Post") != -1) {
                var matches = loc.search.match(/.*(\?|\&)t=(\d*)(\&)?.*/);
                if (matches != null && matches[2] != null) return matches[2];
            }        
        }
    } catch (e) { return null; }
    return null;
  },
  tryParseForumId: function () {
    var loc = content.window.location;
    try {
        if (loc.host == "forum.vingrad.ru") {
            if (loc.pathname.indexOf (".html") != -1) { // ЧПУ
                var matches = loc.pathname.match(/.*\/f(orum)?-(\d+)(\/|\.html).*/);
                if (matches != null && matches[2] != null) 
                    return matches[2];
                else
                    return this.tryParseRewritedForumId (loc.href);
            } else if (loc.search.indexOf ("showforum") != -1) {
                var matches = loc.search.match(/.*(\?|\&)showforum=(\d*)(\&)?.*/);
                if (matches != null && matches[2] != null) return matches[2];
            } else if (loc.search.indexOf ("act=Post") != -1) {
                var matches = loc.search.match(/.*(\?|\&)f=(\d*)(\&)?.*/);
                if (matches != null && matches[2] != null) return matches[2];
            }        
        }
    } catch (e) { return null; }
    return null;
  },
  tryParseRewritedForumId: function (url) {
    var xmlForums = forumsManager.forumsXml;
    if (xmlForums == null) xmlForums = xmlhelper.load (settings.getForumListUrl ()); 
    var forumId = xmlForums.evaluate("//forum[@url='" + url + "']/@id", xmlForums, null, XPathResult.STRING_TYPE, null).stringValue; 
    if (forumId != null && forumId != "")
        return forumId;
    else
        return null;
  },
  tryParseTopicTitle: function () {
    var windowTitle = content.document.title;
    if (windowTitle.indexOf("VPF::") == -1) return windowTitle;
    if (windowTitle.indexOf("VPF::Ответ в ") != -1) return windowTitle.substring(13, windowTitle.length - 30); // отрезаем "VPF::Ответ в "
    return windowTitle.substring(5, windowTitle.length - 30); // Отрезаем "VPF::" и "- Форум прогр-в в-д"
  }
}
